<template>
  <div class="user-management">
    <!-- 搜索栏 -->
    <art-search-bar
      :search-config="searchConfig"
      @search="handleSearch"
      @reset="handleReset"
    />

    <!-- 操作按钮 -->
    <div class="operation-bar">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        新增用户
      </el-button>
      <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
        <el-icon><Delete /></el-icon>
        批量删除
      </el-button>
    </div>

    <!-- 数据表格 -->
    <art-table
      ref="tableRef"
      :columns="columns"
      :data="tableData"
      :loading="loading"
      :pagination="pagination"
      @selection-change="handleSelectionChange"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
    />

    <!-- 用户表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="formData.realName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="formData.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="formData.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete } from '@element-plus/icons-vue'
import { userApi } from '@/api/exampleApi'

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const selectedRows = ref<any[]>([])
const tableData = ref<any[]>([])
const tableRef = ref()

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 搜索配置
const searchConfig = [
  {
    type: 'input',
    label: '用户名',
    prop: 'username',
    placeholder: '请输入用户名'
  },
  {
    type: 'input',
    label: '姓名',
    prop: 'realName',
    placeholder: '请输入姓名'
  },
  {
    type: 'select',
    label: '状态',
    prop: 'status',
    options: [
      { label: '全部', value: '' },
      { label: '启用', value: 1 },
      { label: '禁用', value: 0 }
    ]
  }
]

// 表格列配置
const columns = [
  { type: 'selection', width: 50 },
  { prop: 'username', label: '用户名', width: 120 },
  { prop: 'realName', label: '姓名', width: 120 },
  { prop: 'email', label: '邮箱', width: 200 },
  { prop: 'phone', label: '手机号', width: 150 },
  {
    prop: 'status',
    label: '状态',
    width: 100,
    render: (row: any) => {
      return row.status === 1 ? (
        <el-tag type="success">启用</el-tag>
      ) : (
        <el-tag type="danger">禁用</el-tag>
      )
    }
  },
  { prop: 'createTime', label: '创建时间', width: 180 },
  {
    prop: 'action',
    label: '操作',
    width: 200,
    render: (row: any) => {
      return (
        <>
          <el-button type="primary" size="small" onClick={() => handleEdit(row)}>
            编辑
          </el-button>
          <el-button type="danger" size="small" onClick={() => handleDelete(row)}>
            删除
          </el-button>
        </>
      )
    }
  }
]

// 表单数据
const formData = reactive({
  id: '',
  username: '',
  realName: '',
  email: '',
  phone: '',
  status: 1
})

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ]
}

const formRef = ref()

// 获取用户列表
const getUserList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.current,
      size: pagination.size,
      ...searchParams.value
    }
    const res = await userApi.getUserList(params)
    tableData.value = res.list
    pagination.total = res.total
  } catch (error) {
    console.error('获取用户列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索参数
const searchParams = ref({})

// 搜索处理
const handleSearch = (params: any) => {
  searchParams.value = params
  pagination.current = 1
  getUserList()
}

// 重置处理
const handleReset = () => {
  searchParams.value = {}
  pagination.current = 1
  getUserList()
}

// 分页处理
const handlePageChange = (page: number) => {
  pagination.current = page
  getUserList()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  getUserList()
}

// 选择处理
const handleSelectionChange = (rows: any[]) => {
  selectedRows.value = rows
}

// 新增用户
const handleAdd = () => {
  dialogTitle.value = '新增用户'
  dialogVisible.value = true
  Object.assign(formData, {
    id: '',
    username: '',
    realName: '',
    email: '',
    phone: '',
    status: 1
  })
}

// 编辑用户
const handleEdit = (row: any) => {
  dialogTitle.value = '编辑用户'
  dialogVisible.value = true
  Object.assign(formData, row)
}

// 删除用户
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm('确定要删除该用户吗？', '提示', {
      type: 'warning'
    })
    await userApi.deleteUser(row.id)
    ElMessage.success('删除成功')
    getUserList()
  } catch (error) {
    console.error('删除失败:', error)
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的用户')
    return
  }
  
  try {
    await ElMessageBox.confirm(`确定要删除选中的 ${selectedRows.value.length} 个用户吗？`, '提示', {
      type: 'warning'
    })
    
    // 这里可以调用批量删除接口
    const ids = selectedRows.value.map(row => row.id)
    // await userApi.batchDelete(ids)
    
    ElMessage.success('删除成功')
    getUserList()
  } catch (error) {
    console.error('批量删除失败:', error)
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (formData.id) {
      // 编辑
      await userApi.updateUser(formData.id, formData)
      ElMessage.success('更新成功')
    } else {
      // 新增
      await userApi.createUser(formData)
      ElMessage.success('创建成功')
    }
    
    dialogVisible.value = false
    getUserList()
  } catch (error) {
    console.error('提交失败:', error)
  } finally {
    submitLoading.value = false
  }
}

// 对话框关闭
const handleDialogClose = () => {
  formRef.value?.resetFields()
}

// 页面加载时获取数据
onMounted(() => {
  getUserList()
})
</script>

<style lang="scss" scoped>
.user-management {
  padding: 20px;
  
  .operation-bar {
    margin: 16px 0;
    display: flex;
    gap: 12px;
  }
}
</style>
